package core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;

public class UserDataBase {

    private Vector<String> usersnames;
    private Vector<String> usershashs;
    private String usersFileName;

    public UserDataBase(String file) {
	usersFileName = file;
	load();
    }

    public void store() {

	File usersFile = new File(usersFileName);

	try {
	    if (!usersFile.exists()) {
		usersFile.createNewFile();
	    }

	    FileOutputStream out = new FileOutputStream(usersFile);
	    ObjectOutputStream novoArquivo = new ObjectOutputStream(out);
	    novoArquivo.writeObject(usersnames);
	    novoArquivo.writeObject(usershashs);
	    novoArquivo.flush();
	    novoArquivo.close();
	} catch (Exception e) {
	    e.printStackTrace();
	    System.exit(1);
	}
    }

    @SuppressWarnings("unchecked")
    private void load() {
	try {

	    if (usersnames == null) {
		usersnames = new Vector<String>();
		usershashs = new Vector<String>();
	    }

	    FileInputStream in = null;

	    File usersFile = new File(usersFileName);

	    if (!usersFile.exists()) {
		usersFile.createNewFile();
		store();
		return;
	    }

	    in = new FileInputStream(usersFile);

	    ObjectInputStream arquivo = new ObjectInputStream(in);
	    Object read = arquivo.readObject();
	    Object uh = arquivo.readObject();
	    if (read != null && uh != null && read instanceof Vector<?> && uh instanceof Vector<?>) {
		usersnames.addAll(((Vector<String>) read));
		usershashs.addAll(((Vector<String>) uh));
	    } else {
		throw new Exception("Arquivo de Persistencia Invalido");
	    }

	    arquivo.close();
	    in.close();
	} catch (Exception e) {
	    e.printStackTrace();
	    System.exit(1);
	}
    }

    public void reload() {
	load();
    }

    public boolean hasUser(Usuario usuario) {
	boolean exists = usershashs.indexOf(usuario.getHash()) > -1;
	return exists;
    }

    public boolean hasUserName(Usuario usuario) {
	boolean exists = usersnames.indexOf(usuario.getNomeHash()) > -1;
	return exists;
    }

    public void cadastra(Usuario usuario) {
	usersnames.add(usuario.getNomeHash());
	usershashs.add(usuario.getHash());
	store();
    }

    public void descadastra(Usuario del) {
	del.getTaskFile().delete();
	usersnames.remove(del.getNomeHash());
	usershashs.remove(del.getHash());
	store();
    }
}
